//
//  DLAddressSelectionViewController.m
//  DGGUISpaceSDK
//
//  Created by 伍明鹏 on 2019/12/12.
//

#import "DLAddressSelectionViewController.h"
#import "DLAddressSelectionOption.h"
#import <DGGUIKit/DGGUIKitPrefixHeader.h>

//选项字体
#define kOptiongFont [UIFont systemFontOfSize:14]
//选项高度
#define kOptionHeight self.scrollView.frame.size.height-1
//动画方向
typedef NS_ENUM(NSInteger,Direction) {
    DirectionNone,          //无动画
    DirectionRight2Left,    //从右往左
    DirectionLeft2Right,    //从左往右
};
//选项内间距
static CGFloat const kTitleMargin = 10.0f;
//动画时长
static CGFloat const kAnimationDuration = 0.3f;
//选项初始tag值
static NSInteger const kStartTag = 1000;
//cell标识符
static NSString * const kOptionCellIdentifer = @"DLAddressSelectionCell";

@interface DLAddressSelectionViewController () <UITableViewDelegate, UITableViewDataSource, CAAnimationDelegate>
    
//工具栏
@property (weak, nonatomic) IBOutlet UIView *toolView;
//白色背景View
@property (weak, nonatomic) IBOutlet UIView *backView;
//白色背景View高度约束 (默认400)
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightLayout;
//白色背景View距self.view底部的高度约束 (默认0)
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;
//标题框
@property (weak, nonatomic) IBOutlet UILabel *titleLab;
//关闭按钮
@property (weak, nonatomic) IBOutlet UIButton *closeBtn;
//多选确认按钮
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
//展示已选项数组的scrollView
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
//活动指示器 在有回调时展示
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
//标题下面横线
@property (weak, nonatomic) IBOutlet UIView *titleBottomLineView;
//scroll下横线
@property (weak, nonatomic) IBOutlet UIView *scrollBottomView;
//默认按钮
@property (nonatomic, strong) UIButton *defaultBtn;
//下标,指示选中的按钮
@property (nonatomic, strong) UIView *subscriptView;
//选中的按钮
@property (nonatomic, strong) UIButton *selectedBtn;
//是否正在更新已选项 默认:NO
@property (nonatomic, assign) BOOL updatingSelectedOptions;
//是否正在更新待选项 默认:NO
@property (nonatomic, assign) BOOL updatingDisplayOptions;
//动画方向
@property (nonatomic, assign) Direction reloadDirection;

@end

@implementation DLAddressSelectionViewController

//- (void)dealloc
//{
//    NSLog(@"DLAddressSelectionViewController is dealloc");
//}

//- (void)viewDidLoad {
//    [super viewDidLoad];
//    [self initSubviews];
//}

+ (instancetype)initAddressSelectionView {
//    NSBundle *bundle = [NSBundle bundleWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@""]];
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[DLAddressSelectionViewController class]] pathForResource:@"AddressSelectorBundle" ofType:@"bundle"]];
     DLAddressSelectionViewController * chooseCityView = [bundle loadNibNamed:NSStringFromClass(DLAddressSelectionViewController.class) owner:DLAddressSelectionViewController.class options:nil].firstObject;
    chooseCityView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    chooseCityView.tableView.delegate = chooseCityView;
    chooseCityView.tableView.dataSource = chooseCityView;
    chooseCityView.tableView.backgroundColor = [[DLThemeAdapter shareInstance] dynamicColor:[UIColor whiteColor] darkColor:[UIColor colorWithHex:0x2D2D2E]];
    chooseCityView.backView.width = SCREEN_WIDTH;
    return chooseCityView;
}
//
//    DLAddressSelectionViewController * chooseCityView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(DLAddressSelectionViewController.class) owner:nil options:nil].firstObject;
    
//    DLCChooseCityView *chooseCityView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(DLCChooseCityView.class) owner:nil options:nil].firstObject;
//    chooseCityView.collectionView.transform = CGAffineTransformMakeTranslation(0, -kContentHeight);
//    chooseCityView.collectionView.delegate = chooseCityView;
//    chooseCityView.collectionView.dataSource = chooseCityView;
//    chooseCityView.collectionView.showsVerticalScrollIndicator = NO;
//    [chooseCityView.collectionView registerClass:[DLCChooseCityCollectionViewCell class] forCellWithReuseIdentifier:@"DLCChooseCityCollectionViewCell"];
//    chooseCityView.titleLab.text = title;
//
//    NSString *firstNum = [NSString stringWithFormat:@"%f",(SCREEN_WIDTH - 64)];
//    NSString *secondNum = [NSString stringWithFormat:@"%d",3];
//    NSDecimalNumber *oneNum = [NSDecimalNumber decimalNumberWithString:firstNum];
//    NSDecimalNumber *twoNum = [NSDecimalNumber decimalNumberWithString:secondNum];
//    NSDecimalNumber *division= [oneNum decimalNumberByDividingBy:twoNum];
//    CGFloat itemWith = division.floatValue;
//
//    chooseCityView.layout.itemSize = CGSizeMake(itemWith, 36);
//    chooseCityView.layout.minimumInteritemSpacing = 12;
//    chooseCityView.layout.minimumLineSpacing = 12;
//    chooseCityView.cityArray = cityArray;
//
//    chooseCityView.backViewHeight.constant = kContentHeight;
//    chooseCityView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
//    chooseCityView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
//    [[UIApplication sharedApplication].keyWindow addSubview:chooseCityView];
//    chooseCityView.hidden = NO;
//    [UIView animateWithDuration:0.3 animations:^{
//        chooseCityView.collectionView.transform = CGAffineTransformIdentity;
//        chooseCityView.alpha = 1;
//    } completion:nil];
//    return chooseCityView;
//}

//- (void)awakeFromNib{
//    [super awakeFromNib];
//}

//初始化子视图
- (void)initSubviews
{
    if (self.showTitle) {
        self.titleLab.text = self.showTitle;
    }
    if (self.titleFont) {
        self.titleLab.font = self.titleFont;
    }
    if (self.titleColor) {
        self.titleLab.textColor = self.titleColor;
    }
    if (self.closeImg) {
        [self.closeBtn setImage:self.closeImg forState:UIControlStateNormal];
        [self.closeBtn setTitle:@"" forState:UIControlStateNormal];
    }
    
    self.backView.backgroundColor = [[DLThemeAdapter shareInstance] dynamicColor:[UIColor whiteColor] darkColor:[UIColor colorWithHex:0x2D2D2E]];
    self.toolView.backgroundColor = [[DLThemeAdapter shareInstance] dynamicColor:[UIColor whiteColor] darkColor:[UIColor colorWithHex:0x2D2D2E]];
    _tableView.backgroundColor = [[DLThemeAdapter shareInstance] dynamicColor:[UIColor whiteColor] darkColor:[UIColor colorWithHex:0x2D2D2E]];
    
    //设置左右上圆角
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.backView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(15, 15)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.backView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.backView.layer.mask = maskLayer;
    
    self.activityIndicator.color = self.tintColor;
    self.activityIndicator.hidesWhenStopped = YES;
    
    [self.scrollView addSubview:self.defaultBtn];
    [self.scrollView addSubview:self.subscriptView];
    self.titleBottomLineView.backgroundColor = self.lineColor;
    self.titleBottomLineView.hidden = YES;
    self.scrollBottomView.backgroundColor = self.lineColor;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kOptionCellIdentifer];
    
    UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(reloadItemTableViewForRightSwipe)];
    [_tableView addGestureRecognizer:rightSwipe];
    
    UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(reloadItemTableViewForLeftSwipe)];
    leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
    [_tableView addGestureRecognizer:leftSwipe];
    
    if (self.multiselect) {
        self.confirmBtn.hidden = NO;
        self.selectedOption = [self.chooseOptions firstObject];
    }
    
    //展示时默认调用一次获取待选项数组的Block
    NSAssert(self.displayOptionsBlock, @"displayOptionsBlock未实现");
    self.updatingDisplayOptions = YES;
    self.displayOptionsBlock(self.selectedOption, NO);
    
    //如果有已选项调用获取已选项数组的Block
    if (self.selectedOption) {
        NSAssert(self.selectedOptionsBlock, @"selectedOptionsBlock未实现");
        self.updatingSelectedOptions = YES;
        self.selectedOptionsBlock(self.selectedOption);
    } else {
        self.selectedBtn = self.defaultBtn;
    }
    [self.activityIndicator startAnimating];
}

//根据文字内容获取选项宽度
- (CGFloat)getWidthWithText:(NSString *)text
{
    return [text boundingRectWithSize:CGSizeMake(MAXFLOAT, kOptiongFont.lineHeight) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:kOptiongFont} context:nil].size.width + kTitleMargin*2;
}

#pragma mark - Actions

/**
 设置已选择按钮
 
 @param selectedBtn 已选择按钮
 @param getDisplayOptions 是否需要获取待选项数组
 */
- (void)setSelectedBtn:(UIButton *)selectedBtn getDisplayOptions:(BOOL)getDisplayOptions
{
    if (self.activityIndicator.isAnimating) {//如果活动指示器正在活动,不做操作
        return;
    }
    if (!_selectedBtn) {
        _selectedBtn = selectedBtn;
        return;
    }
    if (selectedBtn == _selectedBtn) {
        return;
    }
    
    _selectedBtn = selectedBtn;
    //确定动画方向
    CGFloat beforeX = self.subscriptView.frame.origin.x;
    CGFloat afterX = selectedBtn.frame.origin.x+kTitleMargin;
    if (beforeX < afterX) {
        self.reloadDirection = DirectionRight2Left;
        if (getDisplayOptions) {
            CGFloat maxX = self.selectedBtn.frame.origin.x + self.selectedBtn.frame.size.width;
            if (maxX-self.scrollView.frame.size.width > self.scrollView.contentOffset.x) {
                [self.scrollView setContentOffset:CGPointMake(maxX-self.scrollView.frame.size.width, 0) animated:YES];
            }
        }
    } else if (beforeX > afterX) {
        self.reloadDirection = DirectionLeft2Right;
        if (getDisplayOptions) {
            if (self.selectedBtn.frame.origin.x < self.scrollView.contentOffset.x) {
                [self.scrollView setContentOffset:CGPointMake(self.selectedBtn.frame.origin.x, 0) animated:YES];
            }
        }
    } else {
        self.reloadDirection = DirectionNone;
    }
    
    //获取待选项数组 如果已选择按钮是默认按钮则取最后已选项的下一级,否则取已选项的当前级
    if (getDisplayOptions) {
        DLAddressSelectionOption *option;
        if (selectedBtn == self.defaultBtn) {
            option = [self.selectedOptions lastObject];
        } else {
            option = self.selectedOptions[selectedBtn.tag-kStartTag];
        }
        [self.activityIndicator startAnimating];
        self.displayOptionsBlock(option, selectedBtn == self.defaultBtn);
    }
    
    [UIView animateWithDuration:kAnimationDuration animations:^{
        self.subscriptView.frame = CGRectMake(afterX, kOptionHeight, selectedBtn.frame.size.width-kTitleMargin*2, 1);
        for (UIButton *button in self.scrollView.subviews) {//移除除默认选项和下标的所有子视图
            if (button != selectedBtn && [button isKindOfClass:[UIButton class]]) {
                [button setTitleColor:self.scrollViewTitleColor ? self.scrollViewTitleColor : [[DLThemeAdapter shareInstance] dynamicColor:CREATCOLORWITHSTRING(@"#000000") darkColor:CREATCOLORWITHSTRING(@"#E0E0E0")] forState:UIControlStateNormal];
            }
        }
        [selectedBtn setTitleColor:self.tintColor forState:UIControlStateNormal];
    }];
}

- (void)updateSelectedOptions:(NSMutableArray *)selectedOptions
{
    [self updateSelectedOptions:selectedOptions showDefaultBtn:NO animation:NO];
}

/**
 更新已选项数组
 
 @param selectedOptions 已选项数组
 @param show 是否展示默认按钮
 @param animation 是否动画展示
 */
- (void)updateSelectedOptions:(NSMutableArray *)selectedOptions showDefaultBtn:(BOOL)show animation:(BOOL)animation
{
    self.updatingSelectedOptions = NO;
    if (!self.updatingDisplayOptions) {//如果没有更新待选项数组则活动指示器停止动画
        [self.activityIndicator stopAnimating];
    }
    self.selectedOptions = selectedOptions;
    
    for (UIView *subview in self.scrollView.subviews) {//移除除默认选项和下标的所有子视图
        if (subview != self.defaultBtn && subview != self.subscriptView) {
            [subview removeFromSuperview];
        }
    }
    
    //如果有已选项数组则创建已选项按钮
    if (selectedOptions.count > 0) {
        CGFloat startX = 0;
        for (int i=0; i<selectedOptions.count; i++) {
            DLAddressSelectionOption *option = selectedOptions[i];
            UIButton *optionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [optionBtn setTitle:option.name forState:UIControlStateNormal];
            [optionBtn setTitleColor:[[DLThemeAdapter shareInstance] dynamicColor:CREATCOLORWITHSTRING(@"#000000") darkColor:CREATCOLORWITHSTRING(@"#E0E0E0")] forState:UIControlStateNormal];
            optionBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            optionBtn.tag = kStartTag + i;
            CGFloat width = [self getWidthWithText:option.name];
            optionBtn.frame = CGRectMake(startX, 0, width, kOptionHeight);
            [optionBtn addTarget:self action:@selector(setSelectedBtn:) forControlEvents:UIControlEventTouchUpInside];
            [self.scrollView addSubview:optionBtn];
            
            if (i == selectedOptions.count-1) {
                if (show) {
                    if (self.defaultBtn.hidden) {//如果默认按钮之前是隐藏的则设置默认按钮的位置
                        self.defaultBtn.frame = CGRectMake(startX+width, 0, self.defaultBtn.frame.size.width, kOptionHeight);
                    }
                    self.defaultBtn.hidden = NO;
                    [self.scrollView bringSubviewToFront:self.selectedBtn];
                    [self setSelectedBtn:self.defaultBtn getDisplayOptions:NO];
                    if (animation) {
                        [UIView animateWithDuration:kAnimationDuration animations:^{
                            self.defaultBtn.frame = CGRectMake(startX+width, 0, self.defaultBtn.frame.size.width, kOptionHeight);
                            self.subscriptView.frame = CGRectMake(startX+width+kTitleMargin, kOptionHeight, self.defaultBtn.frame.size.width-kTitleMargin*2, 1);
                        }];
                    } else {
                        self.defaultBtn.frame = CGRectMake(startX+width, 0, self.defaultBtn.frame.size.width, kOptionHeight);
                        self.subscriptView.frame = CGRectMake(startX+width+kTitleMargin, kOptionHeight, self.defaultBtn.frame.size.width-kTitleMargin*2, 1);
                    }
                    startX += self.defaultBtn.frame.size.width;
                } else {
                    self.defaultBtn.hidden = YES;
                    self.selectedBtn = optionBtn;
                    if (animation) {
                        [UIView animateWithDuration:kAnimationDuration animations:^{
                            self.subscriptView.frame = CGRectMake(startX+kTitleMargin, kOptionHeight, width-kTitleMargin*2, 1);
                        }];
                    } else {
                        self.subscriptView.frame = CGRectMake(startX+kTitleMargin, kOptionHeight, width-kTitleMargin*2, 1);
                        for (UIButton *button in self.scrollView.subviews) {//移除除默认选项和下标的所有子视图
                            if (button != optionBtn && [button isKindOfClass:[UIButton class]]) {
                                [button setTitleColor:self.scrollViewTitleColor ? self.scrollViewTitleColor : [UIColor blackColor] forState:UIControlStateNormal];
                            }
                        }
                        [optionBtn setTitleColor:self.tintColor forState:UIControlStateNormal];
                    }
                }
                _scrollView.contentSize = CGSizeMake(startX+width, 0);
                if (self.scrollView.contentSize.width > self.scrollView.frame.size.width) {
                    _scrollView.contentOffset = CGPointMake(_scrollView.contentSize.width-self.scrollView.frame.size.width, 0);
                }
            }
            startX += width;
        }
    } else {//没有已选项展示默认按钮
        self.defaultBtn.hidden = NO;
        self.selectedBtn = self.defaultBtn;
    }
}

- (void)updateDisplayOptions:(NSMutableArray *)displayOptions
{
    self.updatingDisplayOptions = NO;
    if (!self.updatingSelectedOptions) {
        [self.activityIndicator stopAnimating];
    }
    if (displayOptions.count == 0) {
        self.selectedOption.lastLevel = YES;
        [self dismimss];
    } else {
        self.displayOptions = displayOptions;
        [self reloadItemTableViewWithDirection:self.reloadDirection];
    }
}

- (void)updateDisplayOptions:(NSMutableArray *)displayOptions autoDisMiss:(BOOL)dismiss{
    
}

- (void)selectWithItem:(DLAddressSelectionOption *)item{
    NSInteger index = [self.displayOptions indexOfObject:item];
    if(index < self.displayOptions.count){
        [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    }
}

#pragma mark - Animations
//向左更新ItemTableView
- (void)reloadItemTableViewForLeftSwipe
{
    if (self.activityIndicator.isAnimating) {
        return;
    }
    if (self.defaultBtn.hidden) {
        if (self.selectedBtn.tag-kStartTag == self.selectedOptions.count-1) {
            return;
        } else {
            self.selectedBtn = [_scrollView viewWithTag:self.selectedBtn.tag+1];
        }
    } else {
        if (self.selectedBtn == self.defaultBtn) {
            return;
        } else if (self.selectedBtn.tag-kStartTag == self.selectedOptions.count-1) {
            self.selectedBtn = self.defaultBtn;
        } else {
            self.selectedBtn = [_scrollView viewWithTag:self.selectedBtn.tag+1];
        }
    }
}

//向右更新ItemTableView
- (void)reloadItemTableViewForRightSwipe
{
    if (self.activityIndicator.isAnimating) {
        return;
    }
    if (self.selectedOptions.count == 0) {
        return;
    }
    if (self.selectedBtn == self.defaultBtn) {
        self.selectedBtn = [_scrollView viewWithTag:self.selectedOptions.count-1+kStartTag];
    } else {
        if (self.selectedBtn.tag == kStartTag) {
            return;
        }
        self.selectedBtn = [_scrollView viewWithTag:self.selectedBtn.tag-1];
    }
}

/**
 动画更新tableview
 
 @param direction 动画方向
 */
- (void)reloadItemTableViewWithDirection:(Direction)direction
{
    if (direction != DirectionNone) {
        CATransition *transition = [CATransition animation];
        transition.type = kCATransitionPush;
        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.fillMode = kCAFillModeForwards;
        transition.duration = kAnimationDuration;
        transition.subtype = direction == DirectionLeft2Right ? kCATransitionFromLeft : kCATransitionFromRight;
        transition.delegate = self;
        [[_tableView layer] addAnimation:transition forKey:@"UITableViewReloadDataAnimationKey"];
    }
    [_tableView reloadData];
    if (self.selectedBtn != self.defaultBtn && self.selectedOptions.count > 0) {
        DLAddressSelectionOption *option = self.selectedOptions[self.selectedBtn.tag-kStartTag];
        NSInteger index = [self.displayOptions indexOfObject:option];
        if (index) {
            NSIndexPath *showIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
            [self.tableView scrollToRowAtIndexPath:showIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
        }
    } else {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

#pragma mark - Show&Dismiss
- (IBAction)dismimss
{
    [self.activityIndicator stopAnimating];
    [UIView animateWithDuration:kAnimationDuration animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
        self.topLayout.constant = 0;
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
//        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

- (void)showInViewController:(UIViewController *)viewController
{
    [self initSubviews];
    viewController.modalPresentationStyle = UIModalPresentationCurrentContext;
    [kApplicationWindow addSubview:self];
    [UIView animateWithDuration:kAnimationDuration animations:^{
        self.backgroundColor = [[DLThemeAdapter shareInstance] dynamicColor:[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.5] darkColor:[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.7]];
        self.topLayout.constant = -self.heightLayout.constant;
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        if (self.activityIndicator.isAnimating && !self.updatingSelectedOptions && !self.updatingDisplayOptions) {
            [self.activityIndicator stopAnimating];
        }
    }];
//    [viewController presentViewController:self animated:NO completion:^{
//        [UIView animateWithDuration:kAnimationDuration animations:^{
//            self.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
//            self.topLayout.constant = -self.heightLayout.constant;
//            [self.view layoutIfNeeded];
//        } completion:^(BOOL finished) {
//            if (self.activityIndicator.isAnimating && !self.updatingSelectedOptions && !self.updatingDisplayOptions) {
//                [self.activityIndicator stopAnimating];
//            }
//        }];
//    }];
}

- (IBAction)confirmChoose
{
    if (self.multiselectComplet) {
        self.multiselectComplet(self.chooseOptions);
    }
    [self dismimss];
}

#pragma mark - UITableViewDataSource&Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.displayOptions.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_cell) {
        UITableViewCell *cell = _cell(indexPath);
        return cell;
    }else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kOptionCellIdentifer forIndexPath:indexPath];
        cell.contentView.backgroundColor = [[DLThemeAdapter shareInstance] dynamicColor:[UIColor whiteColor] darkColor:[UIColor colorWithHex:0x2D2D2E]];
        cell.backgroundColor = [[DLThemeAdapter shareInstance] dynamicColor:[UIColor whiteColor] darkColor:[UIColor colorWithHex:0x2D2D2E]];
        
        cell.textLabel.font = kOptiongFont;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        DLAddressSelectionOption *option = self.displayOptions[indexPath.row];
        if (self.multiselect) {
            BOOL contains = NO;
            for (DLAddressSelectionOption *selectOption in self.chooseOptions) {
                if ([option.oId isEqualToString:selectOption.oId]) {
                    contains = YES;
                    break;
                }
            }
            if (contains) {
                cell.textLabel.text = [NSString stringWithFormat:@"%@   ✓",option.name];
                cell.textLabel.textColor = self.tintColor;
            } else {
                cell.textLabel.text = option.name;
                cell.textLabel.textColor = [[DLThemeAdapter shareInstance] dynamicColor:CREATCOLORWITHSTRING(@"#000000") darkColor:CREATCOLORWITHSTRING(@"#E0E0E0")];
            }
        } else {
            if ([self.selectedOptions containsObject:option]) {
                cell.textLabel.text = [NSString stringWithFormat:@"%@   ✓",option.name];
                cell.textLabel.textColor = self.tintColor;
            } else {
                cell.textLabel.text = option.name;
                cell.textLabel.textColor = [[DLThemeAdapter shareInstance] dynamicColor:CREATCOLORWITHSTRING(@"#000000") darkColor:CREATCOLORWITHSTRING(@"#E0E0E0")];
            }
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.activityIndicator.isAnimating) {
        return;
    }
    if (self.displayOptions) {
        DLAddressSelectionOption *option = self.displayOptions[indexPath.row];
        if (option.lastLevel) {
            self.displayOptionsBlock(option, YES);
            if (self.multiselect) {
                BOOL contains = NO;
                DLAddressSelectionOption *targetOption = nil;
                for (DLAddressSelectionOption *selectOption in self.chooseOptions) {
                    if ([option.oId isEqualToString:selectOption.oId]) {
                        contains = YES;
                        targetOption = selectOption;
                        break;
                    }
                }
                if (contains) {
                    [self.chooseOptions removeObject:targetOption];
                } else {
                    [self.chooseOptions addObject:option];
                }
                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            } else {
                [self dismimss];
            }
        } else {
            if (self.multiselect) {
                [self.chooseOptions removeAllObjects];
            }
            NSMutableArray *selectedOptions;
            if (self.selectedBtn == self.defaultBtn) {
                selectedOptions = self.selectedOptions;
            } else {
                selectedOptions = [self.selectedOptions subarrayWithRange:NSMakeRange(0, self.selectedBtn.tag-kStartTag)].mutableCopy;
            }
            [selectedOptions addObject:option];
            [self updateSelectedOptions:selectedOptions showDefaultBtn:YES animation:YES];
            [self.activityIndicator startAnimating];
            self.displayOptionsBlock(option, YES);
        }
    }
}

#pragma mark - CAAnimationDelegate
- (void)animationDidStart:(CAAnimation *)anim
{
    self.tableView.userInteractionEnabled = NO;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    self.tableView.userInteractionEnabled = YES;
}


#pragma mark - Getter&Setter
- (UIButton *)defaultBtn
    {
        if (!_defaultBtn) {
            NSString *title = @"请选择";
            _defaultBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [_defaultBtn setTitle:title forState:UIControlStateNormal];
            [_defaultBtn setTitleColor:self.tintColor forState:UIControlStateNormal];
            _defaultBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            CGFloat width = [self getWidthWithText:title];
            _defaultBtn.frame = CGRectMake(0, 0, width, kOptionHeight);
            [_defaultBtn addTarget:self action:@selector(setSelectedBtn:) forControlEvents:UIControlEventTouchUpInside];
            
            UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.scrollView.frame.size.width, kOptionHeight)];
            maskView.backgroundColor = self.backView.backgroundColor;
            maskView.userInteractionEnabled = NO;
            [_defaultBtn insertSubview:maskView atIndex:0];
        }
        return _defaultBtn;
    }
    
- (UIView *)subscriptView
    {
        if (!_subscriptView) {
            _subscriptView = [[UIView alloc] initWithFrame:CGRectMake(kTitleMargin, kOptionHeight, self.defaultBtn.frame.size.width-kTitleMargin*2, 1)];
            _subscriptView.backgroundColor = self.tintColor;
        }
        return _subscriptView;
    }
    
- (NSMutableArray<DLAddressSelectionOption *> *)chooseOptions
    {
        if (!_chooseOptions) {
            _chooseOptions = @[].mutableCopy;
        }
        return _chooseOptions;
    }
    
- (NSMutableArray *)selectedOptions
    {
        if (!_selectedOptions) {
            _selectedOptions = @[].mutableCopy;
        }
        return _selectedOptions;
    }
    
- (NSMutableArray *)displayOptions
    {
        if (!_displayOptions) {
            _displayOptions = @[].mutableCopy;
        }
        return _displayOptions;
    }
    
- (UIColor *)tintColor
    {
        if (!_tintColor) {
            _tintColor = [UIColor blueColor];
        }
        return _tintColor;
    }
    
- (void)setSelectedBtn:(UIButton *)selectedBtn
    {
        [self setSelectedBtn:selectedBtn getDisplayOptions:YES];
    }
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
